<?php

namespace app\common\model;

use app\common\service\AgentService;
use think\Db;
use think\Model;


class AgentStock extends Model
{

    

    

    // 表名
    protected $name = 'agent_stock';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
	
	public function agent() {
		return $this->belongsTo('agentShop', 'agent_shop_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function spec() {
		return $this->belongsTo('goodsSpec', 'spec_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	/**
	 * 添加代理库存
	 * @param $userId 用户ID
	 * @param $agentId 代理资料ID
	 * @param $goodsId 商品ID
	 * @param $specId 规格ID
	 * @param $number 数量
	 * @return int|string|true
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function add($userId, $agentId, $goodsId, $specId, $number) {
		$row = $this->where(['user_id' => $userId, 'goods_id' => $goodsId, 'spec_id' => $specId])->find();
		if($row) {
			$res = Db::name('agentStock')
				->where(['id' => $row['id']])
				->setInc('number', $number);
		} else {
			$res = Db::name('agentStock')
				->insert([
					'user_id' => $userId,
					'agent_shop_id' => $agentId,
					'goods_id' => $goodsId,
					'spec_id' => $specId,
					'number' => $number,
					'create_time' => time(),
					'update_time' => time()
				]);
		}
		return $res;
	}
	
	
	/**
	 * 获取代理库存
	 * @param $agentId
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getStockByAgentId($agentId) {
		$rows = Db::name('agentStock')->alias('s')
			->join('goods g', 's.goods_id = g.id', 'left')
			->join('goodsSpec gs', 's.spec_id = gs.id', 'left')
			->field('s.goods_id, s.number, g.area, s.spec_id, g.name as goods_name, g.image, gs.name as spec_name, s.spec_id')
			->where(['s.agent_shop_id' => $agentId])
			->select();
		
		$goods = [];
		if($rows) {
			foreach ($rows as $row) {
				if(!isset($goods[$row['goods_id']])) {
					$goods[$row['goods_id']] = [
						'name' => $row['goods_name'],
						'image' => $row['image'],
						'goods_id' => $row['goods_id'],
						'area' => $row['area'],
						'spec' => []
					];
				}
				
				$goods[$row['goods_id']]['spec'][] = [
					'spec_name' => $row['spec_name'] ? : '数量',
					'number' => $row['number'],
					'spec_id' => $row['spec_id']
				];
			}
		}
		
		return array_values($goods);
	}

	
	/**
	 * 获取代理及下级的现有库存数，最大库存数
	 */
	public function getAgentAndSubStock($agentId, $goodsId, $specId) {
		
		//查找自己的库存设置
		$self = Db::name('goods')->alias('g')
			->join('agentStock as', 'as.goods_id = g.id and as.spec_id = '.$specId, 'left')
			->join('agentShop a', 'as.agent_shop_id = a.id', 'left')
			->join('agentStockSetting ass', 'as.agent_shop_id = ass.agent_id and as.goods_id = ass.goods_id and ass.spec_id = as.spec_id', 'left')
			->join('stockWarning sw', 'a.area = sw.area and sw.level = a.role and as.goods_id = sw.goods_id and sw.spec_id = as.spec_id', 'left')
			->where(['g.id' => $goodsId, 'a.id' => $agentId])
			->field('a.role, as.number as stock_number, ass.number as agent_number, sw.number as global_number, sw.warning_number')
			->find();
		
		//还没有这个商品库存记录的
		if(!$self) {
			$agent = AgentShop::get($agentId);
			$agentSetting = Db::name('agentStockSetting')
				->where(['agent_id' => $agentId, 'goods_id' => $goodsId, 'spec_id' => $specId])
				->find();
			$globalSetting = Db::name('stockWarning')
				->where(['area' => $agent['area'], 'level' => $agent['role'], 'goods_id' => $goodsId, 'spec_id' => $specId])
				->find();
			$self = [
				'role' => $agent['role'],
				'stock_number' => 0,
				'agent_number' => $agentSetting ? $agentSetting ['number'] : 0,
				'global_number' => $globalSetting ? $globalSetting['number'] : 0,
				'warning_number' => $agentSetting ? $agentSetting['warning_number'] : $globalSetting['warning_number'],
			];
		}
		
		switch ($self['role']) {
			case \app\admin\model\User::LEVEL_THEATER:
				$field = 'theater_id';
				break;
			case \app\admin\model\User::LEVEL_CENTER:
				$field = 'center_id';
				break;
			case \app\admin\model\User::LEVEL_WAREHOUSE:
				$field = 'warehouse_id';
				break;
			default:
				$field = '';
		}
		
		$subStock = 0;
		$subMax = 0;
		if($field) {
			$subAgentIds = AgentService::getAgentSubIds($agentId, $field);
			$subStocks = Db::name('agentShop')->alias('a')
				->join('agentStock as', 'as.agent_shop_id = a.id and as.goods_id ='.$goodsId.' and as.spec_id = '.$specId, 'left')
				->join('agentStockSetting ass', 'as.agent_shop_id = ass.agent_id and as.goods_id = ass.goods_id and ass.spec_id = as.spec_id', 'left')
				->join('stockWarning sw', 'a.area = sw.area and sw.level = a.role and as.goods_id = sw.goods_id and sw.spec_id = as.spec_id', 'left')
				->where(['a.id' => ['in', $subAgentIds], 'a.role' => ['neq', \app\admin\model\User::LEVEL_WAREHOUSE]])
				->field('a.role, as.number as stock_number, ass.number as agent_number, sw.number as global_number, sw.warning_number')
				->select();
			
			if($subStocks) {
				foreach ($subStocks as $stock) {
					$subStock += $stock['stock_number'];
					$subMax += $stock['agent_number'] ? : $stock['global_number'];
				}
			}
		}
		
		$selfMaxStock = $self['agent_number'] ? : $self['global_number'];
		return [
			'self_stock' => $self['stock_number'],
			'self_max_stock' => $selfMaxStock,  //最大库存数
			'sub_stock' => $subStock, //下级现在库存数
			'sub_max_stock' => $subMax, //下级所有最大库存数
			'all_stock' => $self['stock_number']+$subStock, //所有库存
//			'all_max_stock' => $selfMaxStock+$subMax, //所有最大库存数
			'all_max_stock' => $selfMaxStock,
			'warning_number' => $self['warning_number']
		];
	}
}
